/*

   MCL PEAR - A component library of the Sigh misc. C library.

   Copyright (c) 2011, Sulaiman A. Mustafa

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.


   TODO:
   implement:
   - fix initialize fix
   - fix help message
   - fix remove
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sqlite3.h>
#include <unistd.h>
#include <errno.h>

#include "stag.h"
#include "sllib.h"

#define STAG_FIND_FILES 0
#define STAG_FIND_TAGS 1

/*SQL*/
#define STAG_DB_SQL_FIND_START "select path, group_concat(tag, ' ') from tags "
#define STAG_DB_SQL_FIND_END "group by path;"
#define STAG_DB_SQL_ADD_CHECK "select * from tags where path=? and tag=?"
#define STAG_DB_SQL_ADD "insert into tags values(?, ?);"
#define STAG_DB_SQL_REMOVE_START "delete from tags where "
#define STAG_DB_SQL_GENERIC_ERROR_MESSAGE "SQL error (please submit a bug report)"
#define ASSERT_SQLITE(X, Y, Z)\
	if((X)!=SQLITE_OK){\
		fprintf(stderr, "<!> %s\n(SQL ERROR: %s)\n", (Y), sqlite3_errmsg(Z));\
		exit(1);\
	}

sqlite3 *db;
sqlite3_stmt *statement;

sqlite3* stag_db_sql_open(){
	sqlite3 *handle;
	char *buffer;
	
	if(!stagBaseDir){
		fprintf(stderr, 
		"Base directory not specified! Please fill in a bug report and how to \n"
		"reproduce the bug. Thank you.\n");
		exit(1);
	}
	buffer=initialize_string(stagBaseDir);
	//buffer=append_string(buffer, STAG_DIR_SEP);
	buffer=append_string(buffer, stagDatabase);
	if(sqlite3_open_v2(buffer, &handle, (STAG_IS_OPTION(STAG_OPTION_INITIALIZE))?(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE):(SQLITE_OPEN_READWRITE), NULL)!=SQLITE_OK){
		fprintf(stderr, 
		"Unable to find/open the tag database.\nSee help for more information.\n"
		"----\nFile: %s\nError: %s.\n----\n", buffer, sqlite3_errmsg(handle));
		exit(1);
	}
	if(STAG_IS_OPTION(STAG_OPTION_INITIALIZE)){
		ASSERT_SQLITE(sqlite3_prepare_v2(handle, "create table tags(path, tag)", -1, &statement, NULL), 
		"Error: Database already initialized.", handle)
		if(sqlite3_step(statement)!=SQLITE_DONE){
			fprintf(stderr, "<!> %s\n(SQL ERROR: %s)\n", "Error: Database already initialized.\n", sqlite3_errmsg(db));
			exit(1);
		}
		sqlite3_finalize(statement);
	}
	free_string(buffer);
	return handle;
}


int stag_db_mod(const char *filename){
	int i, j;
	char *local_sql_statement=NULL;

	
	if (stagOperation&STAG_OP_ADD){
		if(!filename){
			fprintf(stderr, "No filename supplied!\n");
			exit(1);
		}
		if(!stagTagCount){
			fprintf(stderr, "file without any tags supplied. ignoring...\n");
		}
		
		for(i=0;i<stagTagCount;++i){
			ASSERT_SQLITE(sqlite3_prepare_v2(db, STAG_DB_SQL_ADD_CHECK, -1, &statement, NULL), STAG_DB_SQL_GENERIC_ERROR_MESSAGE, db)
			ASSERT_SQLITE(sqlite3_bind_text(statement, 1, filename, -1, NULL), STAG_DB_SQL_GENERIC_ERROR_MESSAGE, db)
			ASSERT_SQLITE(sqlite3_bind_text(statement, 2, stagTagList[i], -1, NULL), STAG_DB_SQL_GENERIC_ERROR_MESSAGE, db)
			if (sqlite3_step(statement)==SQLITE_ROW){/*already in database*/
				sqlite3_finalize(statement);
				continue; 
			} 
			else{
				sqlite3_finalize(statement);
				ASSERT_SQLITE(sqlite3_prepare_v2(db, STAG_DB_SQL_ADD, -1, &statement, NULL), STAG_DB_SQL_GENERIC_ERROR_MESSAGE, db)
				ASSERT_SQLITE(sqlite3_bind_text(statement, 1, filename, -1, NULL), STAG_DB_SQL_GENERIC_ERROR_MESSAGE, db)
				ASSERT_SQLITE(sqlite3_bind_text(statement, 2, stagTagList[i], -1, NULL), STAG_DB_SQL_GENERIC_ERROR_MESSAGE, db)
				if(sqlite3_step(statement)!=SQLITE_DONE){
					fprintf(stderr, "%s: %s\n", STAG_DB_SQL_GENERIC_ERROR_MESSAGE, sqlite3_errmsg(db));
					exit(1);
				}
				sqlite3_finalize(statement);
			}
			
		}
	}
	else if (stagOperation&STAG_OP_REMOVE){
		
		if (stagTagCount){
    		printf("1\n");
			for(i=0, j=1;i<stagTagCount;++i){
				local_sql_statement=initialize_string(STAG_DB_SQL_REMOVE_START);
				if (filename) local_sql_statement=append_string(local_sql_statement, "path=? and tag=?");
				else local_sql_statement=append_string(local_sql_statement, "tag=?");
				ASSERT_SQLITE(sqlite3_prepare_v2(db, local_sql_statement, -1, &statement, NULL), STAG_DB_SQL_GENERIC_ERROR_MESSAGE, db)
				if (filename)	ASSERT_SQLITE(sqlite3_bind_text(statement, j++, filename, -1, NULL), STAG_DB_SQL_GENERIC_ERROR_MESSAGE, db)
				ASSERT_SQLITE(sqlite3_bind_text(statement, j, stagTagList[i], -1, NULL), STAG_DB_SQL_GENERIC_ERROR_MESSAGE, db)
				if(sqlite3_step(statement)!=SQLITE_DONE){
					fprintf(stderr, "%s: %s\n", STAG_DB_SQL_GENERIC_ERROR_MESSAGE, sqlite3_errmsg(db));
					exit(1);
				}
				sqlite3_finalize(statement);	
				free_string(local_sql_statement);		
			}
		}
		else{
			if (filename){
    			printf("2%s\n", filename);
				local_sql_statement=initialize_string(STAG_DB_SQL_REMOVE_START);
				local_sql_statement=append_string(local_sql_statement, "path=?");
				ASSERT_SQLITE(sqlite3_prepare_v2(db, local_sql_statement, -1, &statement, NULL), STAG_DB_SQL_GENERIC_ERROR_MESSAGE, db)
				ASSERT_SQLITE(sqlite3_bind_text(statement, 1, filename, -1, NULL), STAG_DB_SQL_GENERIC_ERROR_MESSAGE, db)
				if(sqlite3_step(statement)!=SQLITE_DONE){
					fprintf(stderr, "%s: %s\n", STAG_DB_SQL_GENERIC_ERROR_MESSAGE, sqlite3_errmsg(db));
					exit(1);
				}
				sqlite3_finalize(statement);	
				free_string(local_sql_statement);
			}
		}
	}
	else{
		fprintf(stderr, "improper use of db_mod (invalid operation specified) aborting.\n");
		exit(1);
	}
	return 0;
}

struct stringlist* stag_db_find(char *filename){
	static char *local_sql_statement=NULL;
	static char *matching_file=NULL, *matching_tags=NULL;
	static struct stringlist llist[2];
	int i, offset=0;
	int status;

	if (!(stagOperation&STAG_OP_FIND)){
		fprintf(stderr, "improper use of db_find (invalid operation specified) aborting.\n");
		exit(1);	
	}

	/* 0. Memmory managment ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
	if(local_sql_statement) local_sql_statement=free_string(local_sql_statement);
	if(matching_file) matching_file=free_string(matching_file);
	if(matching_tags) matching_file=free_string(matching_file);

	free_stringlist(&(llist[STAG_FIND_FILES]));
	free_stringlist(&(llist[STAG_FIND_TAGS]));
	
	initialize_stringlist(&(llist[STAG_FIND_FILES]));
	initialize_stringlist(&(llist[STAG_FIND_TAGS]));

	/* 1. Building the sql statement ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
	local_sql_statement=initialize_string(STAG_DB_SQL_FIND_START);
	if(filename || stagTagCount) local_sql_statement=append_string(local_sql_statement, "where ");
	if(filename){
		local_sql_statement=append_string(local_sql_statement, "path=? ");
		if (stagTagCount) local_sql_statement=append_string(local_sql_statement, "and "); 
	}
	if(stagTagCount){
		for(i=0; i<stagTagCount; ++i){
			if(i) local_sql_statement=append_string(local_sql_statement, "and "); 
			local_sql_statement=append_string(local_sql_statement, "tag=? ");
		}
	}
	local_sql_statement=append_string(local_sql_statement, STAG_DB_SQL_FIND_END);
	ASSERT_SQLITE( sqlite3_prepare_v2(db, local_sql_statement, -1, &statement, NULL), STAG_DB_SQL_GENERIC_ERROR_MESSAGE, db)
	if(filename){
		ASSERT_SQLITE(sqlite3_bind_text(statement, 1, filename, -1, NULL), STAG_DB_SQL_GENERIC_ERROR_MESSAGE, db);
		offset=1;
	}
	else offset=0;
	for(i=0; i<stagTagCount; ++i){ /*filling in paramatric values*/
		ASSERT_SQLITE(sqlite3_bind_text(statement, i+offset+1, stagTagList[i], -1, NULL), STAG_DB_SQL_GENERIC_ERROR_MESSAGE, db)
	}
	
	/* 2. Fetching data from database  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/	
	while(1){
		status=sqlite3_step(statement);
		if(status==SQLITE_DONE) break;
		else if (status==SQLITE_ROW){
			matching_file=initialize_string(""); /*these string are freed along with the returned stringlist*/
			matching_file=append_string(matching_file, sqlite3_column_text(statement, 0));
			matching_tags=initialize_string("");
			matching_tags=append_string(matching_tags, sqlite3_column_text(statement, 1));
			
			add_sllib_string_to_stringlist(&(llist[STAG_FIND_FILES]), matching_file);
			add_sllib_string_to_stringlist(&(llist[STAG_FIND_TAGS]), matching_tags);
		}
		else{
			fprintf(stderr, STAG_DB_SQL_GENERIC_ERROR_MESSAGE ": %s\n", sqlite3_errmsg(db));
			exit(1);
		}
	}
	/* 3. DONE ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
	sqlite3_finalize(statement);
	return llist;
}

void stag_db_init(){
	db=stag_db_sql_open();
}


